package cn.com.tom.dao.impl;

import cn.com.tom.dao.BaseDao;
import cn.com.tom.util.Dbs;
import cn.com.tom.util.StringUtils;

import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.List;

public abstract class BaseDaoImpl<T> implements BaseDao<T> {

    private String table = table();

    protected String table() {
        //通过泛型获取表名
        ParameterizedType generic = (ParameterizedType) getClass().getGenericSuperclass();
        String className = ((Class) generic.getActualTypeArguments()[0]).getSimpleName();
        return StringUtils.toLower(className);
    }

    @Override
    public boolean remove(List<Integer> ids) {
        List args = new ArrayList();
        StringBuilder sql = new StringBuilder();
        sql.append("DELETE FROM " + table + " WHERE id in (");
        for (Integer id : ids) {
            sql.append("?,");
            args.add(id);
        }
        sql.replace(sql.length() - 1, sql.length(), ")");
        System.out.println("sql = " + sql);
        return Dbs.save(sql.toString(), args.toArray());
    }

    @Override
    public boolean remove(Integer id) {
        String sql = "DELETE FROM " + table + " WHERE id=?";
        return Dbs.save(sql, id);
    }

    @Override
    public int count() {
        String sql = "SELECT * FROM " + table();
        return Dbs.queryForCount(sql);
    }

}
